#!/user/bin/even Python3
# -*- coding:utf-8 -*-
# CreateFile.py
# 创建文件及入更新表格数据
# author:zhaohexin
# time：2020/7/29 16:48

import os
import datetime

from PyQt5.QtWidgets import QTableWidgetItem

from utility.Management import OpenExcel
from conf import SendHistory


class CreateFlie:
    def __init__(self, datas, mywindow, progressBarValue, progressBarBox):
        self.path = os.path.join(os.path.abspath("."), datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') +
                                 "-查询结果.xlsx")
        self.datas = datas
        self.mywindow = mywindow
        self.progressBarValue = progressBarValue
        self.progressBarBox = progressBarBox

    def save(self):
        """
        进行文件存储及创建
        :return:
        """
        SendHistory.save_path = self.path
        # 删除现有所有行列
        for rowNum in range(0, self.mywindow.tableWidget.rowCount())[::-1]:  # 逆序删除，正序删除会有一些删除不成功
            self.mywindow.tableWidget.removeRow(rowNum)
        with OpenExcel(self.path) as f:
            sheet = f.create_sheet(u"查询结果")
            row = 1
            cum = 1
            # 写入数据
            for data in self.datas:
                # 创建行
                if row > 1:
                    row_cnt = self.mywindow.tableWidget.rowCount()
                    self.mywindow.tableWidget.insertRow(row_cnt)
                for cum_data in data:
                    cum_data = str(cum_data) if cum_data else ""
                    if row > 1:
                        self.mywindow.tableWidget.setItem(row - 2, cum - 1, QTableWidgetItem(cum_data))
                    sheet.cell(row, cum).value = cum_data
                    cum += 1

                row += 1
                cum = 1
                self.progressBarValue.emit((row * 40/len(self.datas)) + 60)  # 发送进度条的值 信号
        self.progressBarBox.emit("1")  # 发送进度条的值 信号


if __name__ == '__main__':
    print(os.path.join(os.path.abspath("."), datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') +
                       "-查询结果.xlsx"))
